<template>
  <div class="table">
    <div class="container">
      <div class="handle-box">

        <el-input v-model="listQuery.name" placeholder="商品" style="width:90px" />
        <el-input v-model="listQuery.category" placeholder="类别" style="width:180px" />
        <el-button type="primary" icon="el-icon-search" :disabled="isDisable" @click="search">搜索</el-button>
        <el-button type="primary" icon="el-icon-search" :disabled="isDisable" @click="handleCreate">添加</el-button>
      </div>
      <div class="table">
        <el-table
          v-loading="listLoading"
          :data="tableData"
          element-loading-text="拼命加载中"
          border
          fit
          highlight-current-row
          style="width: 100%"
          :row-style="{height:'0px'}"
          :cell-style="{padding:'0px'}"
        >
          <el-table-column prop="name" label="商品" />
          <el-table-column prop="price" label="价格" />
          <el-table-column prop="count" label="销量" />
          <el-table-column prop="category" label="类别" />
          <el-table-column prop="description" label="描述" />
          <el-table-column label="照片" width="100px" height="100px" aligin="center">
            <template slot-scope="scope">
              <el-card :body-style="{ padding: '0px' }">
                <img :src="scope.row.icon?scope.row.icon:''" class="image" :onerror="defaultAvatar">
              </el-card>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="200px">
            <template slot-scope="scope">
              <el-button type="text" icon="el-icon-close" class="warnning" @click="close(scope.row)">下架</el-button>
              <el-button type="text" icon="el-icon-delete" class="red" @click="goToDelGoods(scope.row)">编辑</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="page">
          <el-pagination
            v-if="total"
            background
            :current-page="listQuery.pn"
            :page-sizes="[5,10, 20, 25, 30]"
            :page-size="listQuery.ps"
            layout="total, slot, sizes, prev, pager, next, jumper"
            :total="totalNumber"
            @current-change="pageChange"
            @size-change="sizeChange"
          />
        </div>
      </div>
      <!-- 下架提示框 -->
      <el-dialog title="提示" :visible.sync="closeVisible" width="300px" center>
        <div class="del-dialog-cnt">下架不可恢复，是否确定查封？</div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="cancelClose">取 消</el-button>
          <el-button type="primary" @click="closeRow">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  GetOneSellerProductById,
  GetProductByFitFind
} from '@/api/sellermanage/product'
export default {
  name: 'Basetable',
  data() {
    return {
      colors: ['#99A9BF', '#F7BA2A', '#FF9900'], // 等同于 { 2: '#99A9BF', 4: { value: '#F7BA2A', excluded: true }, 5: '#FF9900' }
      multipleSelection: [],
      closeAllVisible: false, // 是否弹出批量删除确认框
      confirmCloseAllVisible: false,
      isDisable: false, // 是否禁用搜索按钮
      closeVisible: false, // 是否弹出查封用户账号的
      addVisible: false, // 是否弹出添加商家弹框
      typeOptions: [], // 商铺类型
      listLoading: false, // 添加商家弹框的loading
      tableData: [{
        id: 1,
        name: '牛肉堡',
        price: 10,
        count: 20,
        description: '好吃的牛肉堡',
        category: '汉堡',
        icon: 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1600945747603&di=ff273c6d378e2db86ecc1748883328d4&imgtype=0&src=http%3A%2F%2Fpic2.16pic.com%2F00%2F36%2F77%2F16pic_3677029_b.jpg',
        sellerId: 0
      }],
      // 查询条件：
      listQuery: {
        pn: 1, // 当前页数 int
        ps: 5, // 每页大小 int
        phone: '',
        category: '',
        name: '',
        address: ''
        // sort: '+id'
      },
      total: undefined, // 总页数
      totalNumber: undefined, // 总条数

      // 查封参数：
      closeList: {
        list: []
      },
      // 添加参数：
      temp: {
        name: '',
        price: '',
        icon: '',
        description: '',
        type: '',
        sellerId: undefined
      }
    }
  },
  computed: {
    defaultAvatar() {
      return 'this.src="' + require('../../../assets/img/elm.png') + '"'
    }
  },
  created() {
    this.listLoading = false
    this.getList()
    // console.log('checkPhone--->' + this.checkPhone('123fvsd'))
  },
  methods: {
    // 分页：
    pageChange(num) {
      this.listQuery.pn = num
      this.getList()
    },
    sizeChange(num) {
      this.listQuery.ps = num
      // this.paginationData.currentPage == 1 && this.requestListData()
      // 每一页改变当前显示条数需要重新请求数据
      this.getList()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    getList() {
      this.listLoading = true
      this.tableData = []
      var params = new URLSearchParams()
      params.append('ps', this.listQuery.ps)
      params.append('pn', this.listQuery.pn)
      var seller_id = sessionStorage.getItem('seller_id')
      params.append('id', seller_id)
      GetOneSellerProductById(params).then(res => {
        this.total = res.ProductList.totalPage
        this.totalNumber = res.ProductList.totalCount
        if (res.ProductList.list !== null && res.ProductList.list.length !== 0) {
          this.tableData = res.ProductList.list
          this.listLoading = false
        } else {
          this.tableData = []
          this.listLoading = false
        }
      }).catch(
        setTimeout(() => {
          this.listLoading = false
        }, 1 * 1000)
      )
    },
    findList() {
      this.listLoading = true
      this.tableData = []
      var params = new URLSearchParams()
      params.append('ps', this.listQuery.ps)
      params.append('pn', this.listQuery.pn)
      params.append('name', this.listQuery.name)
      params.append('category', this.listQuery.category)
      var seller_id = sessionStorage.getItem('seller_id')
      params.append('sellerId', seller_id)
      GetProductByFitFind(params).then(res => {
        this.total = res.ProductList.totalPage
        this.totalNumber = res.ProductList.totalCount
        if (res.ProductList.list !== null && res.ProductList.list.length !== 0) {
          this.tableData = res.ProductList.list
          this.listLoading = false
        } else {
          this.tableData = []
          this.listLoading = false
        }
      }).catch(
        setTimeout(() => {
          this.listLoading = false
        }, 1 * 1000)
      )
    },

    search() {
      this.isDisable = true
      this.tableData = []
      this.findList()
      setTimeout(() => {
        this.isDisable = false // 点击一次时隔两秒后才能再次点击
      }, 2000)
    },
    goToDelGoods(row) {
      // 跳转到查封商品的页面，把参数商家的id传过去
      // this.$router.push({ path: '/usersManagement/delGoods' })
      this.$router.push({
        path: '/usersManagement/delGoods',
        query: {
          id: row.id
        }
      })
    },

    getSellerCategory() {
      // GetAllSellerCategory().then(response => {
      //   if (response.SellerCategoryList !== null) {
      //     this.typeOptions = response.SellerCategoryList
      //   } else {
      //     this.typeOptions = []
      //   }
      // })
    },

    handleCreate() {
      this.resetTemp()
      this.getSellerCategory()
      this.addVisible = true
    },
    saveAdd() {
      // this.listLoading = true
      // this.$refs['temp'].validate((valid) => {
      //   if (valid) {
      //     this.listLoading = true
      //     AddSeller(qs.stringify(this.temp)).then(response => {
      //       if (response.code === 200) {
      //         this.$message.success('添加成功')
      //         this.getList()
      //       } else {
      //         this.$message.warning('添加失败！')
      //       }
      //     }).catch(
      //       setTimeout(() => {
      //         this.listLoading = false
      //         this.addVisible = false
      //       }, 2 * 1000)
      //     )
      //     this.listLoading = false
      //     this.addVisible = false
      //   } else {
      //     this.listLoading = false
      //     return false
      //   }
      // })
    },
    resetTemp() {
      if (this.$refs['temp'] !== undefined) {
        this.$refs['temp'].resetFields()
      }
      this.temp = {
        username: '',
        password: '',
        sellername: '',
        phone: '',
        address: '',
        categoryId: undefined,
        packCost: undefined,
        logo: undefined
      }
    },
    /* 图像*/
    getBase64(file) {
      return new Promise(function(resolve, reject) {
        const reader = new FileReader()
        let imgResult = ''
        reader.readAsDataURL(file)
        reader.onload = function() {
          imgResult = reader.result
        }
        reader.onerror = function(error) {
          reject(error)
        }
        reader.onloadend = function() {
          resolve(imgResult)
        }
      })
    },
    getFile(file, fileList) {
      var that = this
      this.getBase64(file.raw).then(res => {
        that.temp.logo = res
        // that.form.photo = res
        console.log(res)
      })
    }
  }
}
</script>
<style scoped>
  .image {
    /* height: 70px; */
    width: 100%;
    display: block;
  }

  .page {
    margin-top: 1%;
    margin-bottom: 2%;
    float: right;
  }

  .container {
    margin-left: 30px;
    margin-right: 30px;
    margin-top: 30px;
  }

  .handle-box {
    margin-bottom: 20px;
    margin-top: 20px;
  }

  .handle-select {
    width: 120px;
  }

  .handle-input {
    width: 120px;
    display: inline-block;
  }

  .del-dialog-cnt {
    font-size: 16px;
    text-align: center
  }

  .table {
    width: 100%;
    font-size: 14px;
  }

  .red {
    color: #ff0000;
  }

  .warnning {
    color: #bd5a09;
  }

  .mr10 {
    margin-right: 10px;
  }
</style>
